package com.nurt.dao.impl;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import com.nurt.dao.OrderDishDao;
import com.nurt.entity.OrderDishEntity;
import com.nurt.entity.OrderEntity;
import com.nurt.utils.DatabaseManager;

public class OrderDishDaoImpl implements OrderDishDao{
    private Connection conn;

    public OrderDishDaoImpl() {
        try {
            this.conn = DatabaseManager.getInstance().getConnection();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public List<OrderDishEntity> selectOrderDishes(int orderId) throws SQLException {
        String sql = "SELECT * FROM orderDishes WHERE orderId = " + orderId;
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        List<OrderDishEntity> orderDishes = new ArrayList<>();
        while (rs.next()) {
            OrderDishEntity orderDish = new OrderDishEntity();
            orderDish.setOrderDishId(rs.getInt("orderDishId"));
            orderDish.setOrderId(rs.getInt("orderId"));
            orderDish.setDishId(rs.getInt("dishId"));
            orderDish.setName(rs.getString("name"));
            orderDish.setQuantity(rs.getInt("quantity"));
            orderDish.setPrice(rs.getDouble("price"));
            orderDishes.add(orderDish);
        }
        return orderDishes;
    }

    public List<OrderDishEntity> selectOrderDishes(OrderEntity order) throws SQLException {
        return selectOrderDishes(order.getOrderId());
    }

    public int updateOrderDish(OrderDishEntity orderDish) throws SQLException {
        String sql = "UPDATE orderDishes SET orderId = " + orderDish.getOrderId() + ", dishId = " + orderDish.getDishId() + ", name = '" + orderDish.getName() + "', quantity = " + orderDish.getQuantity() + ", price = " + orderDish.getPrice() + " WHERE orderDishId = " + orderDish.getOrderDishId();
        Statement stmt = conn.createStatement();
        return stmt.executeUpdate(sql);
    }

    public int insertOrderDish(OrderDishEntity orderDish) throws SQLException {
        String sql = "INSERT INTO orderDishes (orderId, dishId, name, quantity, price) VALUES (" + orderDish.getOrderId() + ", " + orderDish.getDishId() + ", '" + orderDish.getName() + "', " + orderDish.getQuantity() + ", " + orderDish.getPrice() + ")";
        Statement stmt = conn.createStatement();
        stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
        ResultSet rs = stmt.getGeneratedKeys();
        if (rs.next()) {
            return rs.getInt(1);
        } else {
            throw new SQLException("Creating order dish failed, no ID obtained.");
        }
    }

    public int deleteOrderDish(int orderDishId) throws SQLException {
        String sql = "DELETE FROM orderDishes WHERE orderDishId = " + orderDishId;
        Statement stmt = conn.createStatement();
        return stmt.executeUpdate(sql);
    }
}